package com.shiro.test.mvc.service.impl;

import com.shiro.test.mvc.dao.IBaseDao;
import com.shiro.test.mvc.mapper.UserMapper;
import com.shiro.test.mvc.pojo.User;
import com.shiro.test.mvc.service.IUserService;
import com.shiro.test.mvc.util.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2020/11/26 0026.
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public IBaseDao<User> getDao() {
        return userMapper;
    }

    @Override
    public User doLogin(String email, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(email, password);
        try {
            subject.login(token);
            Session session = subject.getSession();
            User user = getUserByEmail(email);
            session.setAttribute(Constants.SESSION_USER,user);
            return user;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public User getUserByEmail(String email) {
        User user = userMapper.getUserByEmail(email);
        return user;
    }

    @Override
    public List<User> getUserList() {
        return userMapper.getUserList();
    }

    @Override
    public void addUserRole(int userId, int[] roleIds) {
        userMapper.deleteUserRole(userId);
        Map<String,Integer> param = new HashMap<>();
        param.put("userId",userId);
        for (int roleId : roleIds) {
            param.put("roleId",roleId);
            userMapper.addUserRole(param);
        }
    }

    @Override
    public List<Integer> getUserRoles(int userId) {
        return userMapper.getUserRoles(userId);
    }
}
